const userService = require("../service/user.service");
const md5Password = require("../utils/md5-password");
const {
  NAME_OR_PASSWORD_IS_REQUIERD,
  NAME_IS_ALREADY_EXISTS,
} = require("../config/error");

const verifyUser = async (ctx, next) => {
  // 查看存储的结果
  // 判断用户和密码是否为空
  const { name, password } = ctx.request.body;
  if (!name || !password) {
    return ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIERD, ctx);
  }
  // 判断用户是否已经注册
  const users = await userService.findUserName(name);
  if (users.length) {
    return ctx.app.emit("error", NAME_IS_ALREADY_EXISTS, ctx);
  }

  //   执行下一个中间件
  await next();
};

// 密码加密的中间件
const encryption = async (ctx, next) => {
  const { password } = ctx.request.body;
  ctx.request.body.password = md5Password(password);

  await next();
};

module.exports = { verifyUser, encryption };
